package org.gongliang.jfinal.utils;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;


/**
 * @description 字符串工具类
 * @author 龚亮
 * @date 2014-10-15 15:11:24
 */
public class StringUtil extends StrKit{
	

	/**
	* 截取文件后缀
	*/
	public static String subFileName(String fileName) {
	    int index = fileName.lastIndexOf(".");
		return -1==index?fileName:fileName.substring(index + 1);
	}
	public static String subFileNamePrex(String fileName) {
	    int index = fileName.lastIndexOf(".");
		return -1==index?fileName:fileName.substring(0,index);
	}
	/**
	 * 获取随机时间文件名
	 */
	public static String getTimeFileName() {
		return DateFormatUtils.format(new Date(), "yyyyMMddHHmmssS");
	}
	/**
	 * 获取随机uuid文件名
	 */
	public static String getRandomFileName() {
		return UUID.randomUUID().toString();
	}

	/**
	 * prex 前缀目录
	 * 获得日期生成二级目录
	 */
	public static String generateRandomDateDir(String prex) {
		Date date=new Date();
		return prex+ DateFormatUtils.format(date,"yyyy") + "/" + DateFormatUtils.format(date,"MM") + "/" + DateFormatUtils.format(date,"dd") + "/";
	}
	/**
	 * 获得hashcode生成二级目录
	 */
	public static String generateRandomDir(String uuidFileName) {
		int hashCode = uuidFileName.hashCode();
		// 一级目录
		int d1 = hashCode & 0xf;
		// 二级目录
		int d2 = (hashCode >> 4) & 0xf;
		return "/" + d1 + "/" + d2;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String, Object> toMap(Model model) {
		Map<String, Object> map = Maps.newHashMap();
		Set<Entry<String, Object>> attrs = model._getAttrsEntrySet();
		for (Entry<String, Object> entry : attrs) {
			map.put(entry.getKey(), entry.getValue());
		}
		return map;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Record toRecord(Model model) {
		Record record = new Record();
		Set<Entry<String, Object>> attrs = model._getAttrsEntrySet();
		for (Entry<String, Object> entry : attrs) {
			record.set(entry.getKey(), entry.getValue());
		}
		return record;
	}

	/**
	 * 将Record转换成Map recordToMap
	 * 
	 * @param 参数说明
	 * @return 返回对象
	 * @Exception 异常对象
	 */
	public static Map<String, Object> recordToMap(Record record) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (record != null) {
			String[] columns = record.getColumnNames();
			for (String col : columns) {
				map.put(col, record.get(col));
			}
		}
		return map;
	}

	/**
	 * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String && (obj.equals(""))) {
			return true;
		} else if (obj instanceof Short && ((Short) obj).shortValue() == 0) {
			return true;
		} else if (obj instanceof Integer && ((Integer) obj).intValue() == 0) {
			return true;
		} else if (obj instanceof Double && ((Double) obj).doubleValue() == 0) {
			return true;
		} else if (obj instanceof Float && ((Float) obj).floatValue() == 0) {
			return true;
		} else if (obj instanceof Long && ((Long) obj).longValue() == 0) {
			return true;
		} else if (obj instanceof Boolean && !((Boolean) obj)) {
			return true;
		} else if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Map && ((Map) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
			return true;
		}
		return false;
	}

	public static Model<?> toModel(Class<? extends Model<?>> clazz, Record record) {
		Model<?> model = null;
		try {
			model = clazz.newInstance();
		} catch (Exception e) {
			return model;
		}
		for (String columnName : record.getColumnNames()) {
			model.set(columnName, record.get("columnName"));
		}
		return model;
	}

	/**
	 * 将驼峰风格替换为下划线风格
	 */
	public static String camelhumpToUnderline(String str) {
		final int size;
		final char[] chars;
		final StringBuilder sb = new StringBuilder((size = (chars = str.toCharArray()).length) * 3 / 2 + 1);
		char c;
		for (int i = 0; i < size; i++) {
			c = chars[i];
			if (isUppercaseAlpha(c)) {
				sb.append('_').append(toLowerAscii(c));
			} else {
				sb.append(toUpperAscii(c));
			}
		}
		return sb.charAt(0) == '_' ? sb.substring(1) : sb.toString();
	}

	public static char toUpperAscii(char c) {
		if (isUppercaseAlpha(c)) {
			c -= (char) 0x20;
		}
		return c;
	}

	public static char toLowerAscii(char c) {
		if (isUppercaseAlpha(c)) {
			c += (char) 0x20;
		}
		return c;
	}

	/**
	 * 将下划线风格替换为驼峰风格
	 */
	public static String underlineToCamelhump(String str) {
		Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
		StringBuilder builder = new StringBuilder(str);
		for (int i = 0; matcher.find(); i++) {
			builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
		}
		if (Character.isUpperCase(builder.charAt(0))) {
			builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
		}
		return builder.toString();
	}

	public static boolean isUppercaseAlpha(char c) {
		return (c >= 'A') && (c <= 'Z');
	}

	public static boolean isLowercaseAlpha(char c) {
		return (c >= 'a') && (c <= 'z');
	}
}